package com.tangji.signaltower.websocket.session;

import com.alibaba.fastjson.JSONObject;
import com.tangji.signaltower.constant.AttributeConstant;
import com.tangji.signaltower.websocket.model.WebUser;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现服务器Socket Session会话
 * User: Amarendar
 * Date: 2020/6/2
 * Time: 下午2:17
 */
public class ServerSession {
    private static final Logger logger = LoggerFactory.getLogger(ServerSession.class);

    /**
     * session唯一标示
     */
    private String sessionId;
    /**
     * 通道
     */
    private Channel channel;
    /**
     * 用户
     */
    private WebUser webUser;
    /**
     * 订阅列表
     */
    private List<String> subscription = new ArrayList<>();

    public ServerSession(Channel channel, String sessionId) {
        this.channel = channel;
        this.sessionId = sessionId;
        logger.info("ServerSession绑定会话:" + channel.remoteAddress());
        //行情订阅
//        this.subscription = new ArrayList<>();
        //向channel设置session
        channel.attr(AttributeConstant.SESSION_KEY).set(this);
    }

    public String getSessionId() {
        return sessionId;
    }

    public ServerSession setSessionId(String sessionId) {
        this.sessionId = sessionId;
        return this;
    }

    public Channel getChannel() {
        return channel;
    }

    public ServerSession setChannel(Channel channel) {
        this.channel = channel;
        return this;
    }

    public WebUser getWebUser() {
        return webUser;
    }

    public ServerSession setWebUser(WebUser webUser) {
        this.webUser = webUser;
        return this;
    }

    public List<String> getSubscription() {
        return subscription;
    }

    public ServerSession setSubscription(List<String> subscription) {
        this.subscription = subscription;
        return this;
    }

    /**
     * 反向导航
     *
     * @param ctx
     * @return
     */
    public static ServerSession getSession(ChannelHandlerContext ctx) {
        logger.info("==Session==, getSession, ChannelHandlerContext:{}", JSONObject.toJSONString(ctx));

        Channel channel = ctx.channel();
        return channel.attr(AttributeConstant.SESSION_KEY).get();
    }

    /**
     * 反向导航
     *
     * @param channel
     * @return
     */
    public static ServerSession getSession(Channel channel) {
        logger.info("==Session==, getSession, channel:{}", JSONObject.toJSONString(channel));

        return channel.attr(AttributeConstant.SESSION_KEY).get();
    }

    /**
     * 异常处理
     *
     * @param error
     */
    public void processError(Throwable error) {
        //TODO
    }
}
